package com.yqs.JavaWeb;

import com.yqs.JavaWeb.util.DBConnection;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;


/**
 * @project: JavaWeb
 * @package: com.yqs.JavaWeb
 * @Description:
 * @Since: jdk版本号
 * @Author: 逝风岁月
 * @Email: 2637182317@qq.com
 * @Date: 2024-09-11 17:46:14
 */

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        response.setContentType("text/html;charset=UTF-8");

        if (username != null && password != null) {
            try (Connection conn = DBConnection.getConnection()) {
                String sql = "INSERT INTO user (username, password) VALUES (?, ?)";
                PreparedStatement pstmt = conn.prepareStatement(sql);
                pstmt.setString(1, username);
                pstmt.setString(2, password);
                int rowsAffected = pstmt.executeUpdate();

                if (rowsAffected > 0) {
                    response.getWriter().println("注册成功！");
                    PrintWriter printWriter = response.getWriter();
                    printWriter.println("<script>alert('注册成功，请登录！'); location.href='login.jsp';</script>");
                } else {
                    response.getWriter().println("注册失败！");
                    PrintWriter printWriter = response.getWriter();
                    printWriter.println("<script>alert('注册失败！'); location.href='register.jsp';</script>");
                }
            } catch (SQLException e) {
                e.printStackTrace();
                response.getWriter().println("注册失败：" + e.getMessage());
                PrintWriter printWriter = response.getWriter();
                printWriter.println("<script>alert('注册失败！'); location.href='register.jsp';</script>");
            }
        } else {
            response.getWriter().println("请填写所有字段！");
        }
    }
}